'''

	Tools...

'''




import sys
import os, stat, time

class Log:
  def __init__( self, fileName, out=False, err=False ):
    self.replaced = [None,None]
    self.fileName = fileName
    w = open( self.fileName, 'w' )
    w.write( "OPENING LOG: "+self.fileName+"\n\n" )
    w.close()
    self.replace_sys(out,err)

  def replace_sys(self, out=False, err=False ):
    if out:
      self.replaced[0] = sys.stdout
      sys.stdout = self
    if err:
      self.replaced[1] = sys.stderr
      sys.stderr = self

  def restore_sys(self, out=True, err=True ):
    if out and self.replaced[0] is not None:
      sys.stdout = self.replaced[0]
    if err and self.replaced[1] is not None:
      sys.stderr = self.replaced[1]
  
  def write(self, str ):
    w = open( self.fileName, 'a' )
    w.write( str )
    w.close()
    #self.p(str)

  def p(self, *args ):
    for s in args:
      self.replaced[0].write(">>>"+s+"\n")


class LogWatcher:
    def __init__( self, filename ):
        self.filename = filename
        self.mtime = None
        self.len = 0
        
    def start(self):
        while True:
            mtime = os.stat(self.filename)[8]
            if mtime != self.mtime:
                print '##### TOUCHED #####'
                r = open( self.filename, 'r' )
                r.seek(self.len)
                print r.read()
                self.len = r.tell()-1
                r.close()
                self.mtime = mtime
            time.sleep(1)
        
        
        
